<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>首页</title>
  <style type="text/css" media="screen">
  	#previewArea{
  		width: 206px; height: 206px; border: 1px solid red;padding: 2px;box-sizing: border-box;
  	}
  	#previewArea img{
  		width: 200px; height: 200px; 
  	}
  </style>
</head>
<body>
  <div id="previewArea">
  	
  </div>
  <input type="file" id="myFile" name="file">
  <progress id="myProgress" value="0" max="100"> </progress>

  <button onClick="doUpload()">上传</button>
  <script type="text/javascript">
  	function doUpload() {
	  	var xhr = new XMLHttpRequest();
		var formData = new FormData();
		var fileInput = document.getElementById("myFile");
		var file = fileInput.files[0];

		formData.append('file', file);

		xhr.open("POST", "/admin/content/upload");

		xhr.onload = function(r){
		    if(this.status === 200){
				console.log(this.responseText);
		        alert('请求成功！')
		    }
		}
		xhr.upload.onprogress = function(event) {
		    if (event.lengthComputable) {
		        var percentComplete = (event.loaded / event.total) * 100;
		        // 对进度进行处理
		        document.getElementById('myProgress').value = percentComplete;

		        handleImageFile();
		    }
		}


		xhr.send(formData);
		xhr = null;
  	}

  	function handleImageFile() {
	   var previewArea = document.getElementById('previewArea');
	   var img = document.createElement('img');
	   var fileInput = document.getElementById("myFile");
	   var file = fileInput.files[0];
	   // img.file = file;
	   previewArea.appendChild(img);

	   var reader = new FileReader();
	   reader.onload = (function(aImg) {
	        return function(e) {
	             aImg.src = e.target.result;
	        }
	   })(img);
	   reader.readAsDataURL(file);
	}

  </script>
</body>
</html>